module.exports = function(window, document) {
	var apivm = require('../../common/avm.min')(window, document);
	var avm = apivm;
	var api = apivm.api;
	var Component = apivm.Component;
	var $ = apivm.$;
	(function() {
	/*
	 * APICloud JavaScript Library
	 * Copyright (c) 2014 apicloud.com
	 */
	var $kn = {
		byId: function byId(id) {
			return document.getElementById(id);
		},
		ajax: function ajax(p, callback) {
			var _this = this;
			var param = p;
			if (!param.headers) {
				param.headers = {};
			}
			param.headers["x-apicloud-mcm-key"] = "cZKzX7DabDmYyfez";
			if (param.data && param.data.body) {
				param.headers["Content-Type"] = "application/json; charset=utf-8";
			}
			if (param.url) {
				var baseUrl = "https://a8888888888888-pd.apicloud-saas.com/api/";
				param.url = baseUrl + param.url;
			}
			api.ajax(param, function(ret, err) {
				if (callback) callback(ret, err);
				if (ret) {
					var status = ret.status;
					if (status && status == 4001) {
						var didShowLogoutAlert = api.getGlobalData({
							key: "didShowLogoutAlert"
						});

						if (!didShowLogoutAlert) {
							api.setGlobalData({
								key: "didShowLogoutAlert",
								value: true
							});

							_this.setUserInfo("");
							api.alert(
								{
									msg: "登录已失效，请重新登录"
								},
								function() {
									api.setGlobalData({
										key: "didShowLogoutAlert",
										value: false
									});

									api.closeToWin({
										name: "root"
									});
								}
							);
						}
					}
				}
			});
		},
		getUserInfo: function getUserInfo() {
			var value = api.getPrefs({
				key: "userInfo",
				sync: true
			});

			return value ? JSON.parse(value) : "";
		},
		setUserInfo: function setUserInfo(userInfo) {
			api.setPrefs({
				key: "userInfo",
				value: userInfo
			});
		},
		getCurrentCityInfo: function getCurrentCityInfo() {
			var value = api.getPrefs({
				key: "currentCity",
				sync: true
			});

			return value ? JSON.parse(value) : "";
		},
		setCurrentCityInfo: function setCurrentCityInfo(cityInfo) {
			api.setPrefs({
				key: "currentCity",
				value: cityInfo
			});
		},
		getWareTypeList: function getWareTypeList() {
			var value = api.readFile({
				sync: true,
				path: "fs://WareTypeList"
			});

			return value ? JSON.parse(value) : "";
		},
		setWareTypeList: function setWareTypeList(list) {
			api.writeFile({
				path: "fs://WareTypeList",
				data: JSON.stringify(list)
			});
		},
		fitRichText: function fitRichText(richtext, width) {
			var str = '<img style="max-width:' + width + 'px;"';
			var result = richtext.replace(/\<img/gi, str);
			return result;
		}
	};

	var Cityselector = /*@__PURE__*/ (function(Component) {
		function Cityselector(props) {
			Component.call(this, props);
			this.data = {
				dataList: []
			};
		}

		if (Component) Cityselector.__proto__ = Component;
		Cityselector.prototype = Object.create(Component && Component.prototype);
		Cityselector.prototype.constructor = Cityselector;
		Cityselector.prototype.installed = function() {
			this.fnGetCityList();
		};
		Cityselector.prototype.closeAction = function() {
			this.closeFrame();
		};
		Cityselector.prototype.closeFrame = function(currentCity) {
			this.fire("result", currentCity);
		};
		Cityselector.prototype.fnGetCityList = function() {
			var that = this;
			$kn.ajax(
				{
					url: "supportAreas/getSupportAreaList",
					cache: true
				},
				function(ret, err) {
					if (ret && ret.data) {
						var data = ret.data;
						var list = [];
						for (var i = 0; i < data.length; i++) {
							if (data[i].name) {
								list.push(data[i]);
							}
						}
						that.data.dataList = list;
					} else {
						api.toast({
							msg: "获取区域列表失败"
						});
					}
				}
			);
		};
		Cityselector.prototype.fnSelectCity = function(e) {
			var cityInfo = e.currentTarget.dataset.item;
			$kn.setCurrentCityInfo(cityInfo);
			this.closeFrame(cityInfo);
		};
		Cityselector.prototype.render = function() {
			var this$1 = this;
			return apivm.h(
				"view",
				{class: "cityselector-main"},
				apivm.h("safe-area", null),
				apivm.h(
					"text",
					{class: "cityselector-close", onclick: this.closeAction},
					"×"
				),
				apivm.h("text", {class: "cityselector-title"}, "选择所需服务的地区"),
				apivm.h(
					"scroll-view",
					{class: "cityselector-section", "scroll-y": "true"},
					Object.entries(this.data.dataList).map(function(ref) {
						var index$1 = ref[0];
						var item$1 = ref[1];
						return apivm.h(
							"view",
							null,
							apivm.h(
								"text",
								{
									class: "cityselector-city",
									"data-item": item$1,
									onclick: this$1.fnSelectCity
								},
								item$1.name
							)
						);
					})
				)
			);
		};

		return Cityselector;
	})(Component);
	apivm.define("cityselector", Cityselector);

	var StatusBarView = /*@__PURE__*/ (function(Component) {
		function StatusBarView(props) {
			Component.call(this, props);
			this.compute = {
				statusBarHeight: function() {
					if (api.safeArea) {
						return api.safeArea.top;
					} else {
						var res = wx.getSystemInfoSync();
						return res.statusBarHeight;
					}
				}
			};
		}

		if (Component) StatusBarView.__proto__ = Component;
		StatusBarView.prototype = Object.create(Component && Component.prototype);
		StatusBarView.prototype.constructor = StatusBarView;
		StatusBarView.prototype.render = function() {
			return apivm.h("view", {style: "height:" + this.statusBarHeight + "px;"});
		};

		return StatusBarView;
	})(Component);
	apivm.define("status-bar-view", StatusBarView);

	var Minicart = /*@__PURE__*/ (function(Component) {
		function Minicart(props) {
			Component.call(this, props);
			this.data = {
				amount: 0,
				count: 0
			};
		}

		if (Component) Minicart.__proto__ = Component;
		Minicart.prototype = Object.create(Component && Component.prototype);
		Minicart.prototype.constructor = Minicart;
		Minicart.prototype.installed = function() {
			this.initEventListenner();
			if ($kn.getUserInfo()) {
				this.getCartInfo();
			}
		};
		Minicart.prototype.initEventListenner = function() {
			var that = this;
			// 监听onGetCartInfo事件（自定义），更新商品数量和总金额
			api.addEventListener(
				{
					name: "onGetCartInfo"
				},
				function(ret, err) {
					var data = ret.value;
					that.data.amount = Math.floor(data.totalPrice * 10) / 10;
					that.data.count = data.totalCount;
				}
			);
			api.addEventListener(
				{
					name: "onLogin"
				},
				function(ret, err) {
					that.getCartInfo();
				}
			);
			api.addEventListener(
				{
					name: "onLogout"
				},
				function(ret, err) {
					that.data.amount = 0;
					that.data.count = 0;
				}
			);
		};
		Minicart.prototype.fnOpenShoppingCartWin = function() {
			if (!$kn.getUserInfo()) {
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});

				return;
			}
			api.openWin({
				name: "shoppingcart",
				url: "../shoppingcart/shoppingcart.stml"
			});
		};
		Minicart.prototype.getCartInfo = function() {
			$kn.ajax(
				{
					url: "carts/getCartInfo"
				},
				function(ret, err) {
					if (ret && ret.data) {
						api.setGlobalData({key: "cartInfo", value: ret.data});
						api.sendEvent({
							name: "onGetCartInfo",
							extra: ret.data
						});
					}
				}
			);
		};
		Minicart.prototype.render = function() {
			return apivm.h(
				"view",
				{class: "__main", onclick: this.fnOpenShoppingCartWin},
				apivm.h("text", {class: "__amount"}, "￥" + this.data.amount),
				apivm.h(
					"text",
					{class: this.data.count > 0 ? "__count" : "__count __count-none"},
					this.data.count
				)
			);
		};

		return Minicart;
	})(Component);
	apivm.define("minicart", Minicart);

	var Main = /*@__PURE__*/ (function(Component) {
		function Main(props) {
			Component.call(this, props);
			this.data = {
				citySelectorOpened: false,
				cityName: "选择地区",
				cityDataList: [],
				wareTypeList: [],
				currentIndex: 0,
				frames: [],
				dataList: [],
				bannerUrl: "",
				skip: 0,
				haveMoreData: true,
				refresherTriggered: false,
				wareTypeId: ""
			};
		}

		if (Component) Main.__proto__ = Component;
		Main.prototype = Object.create(Component && Component.prototype);
		Main.prototype.constructor = Main;
		Main.prototype.apiready = function() {
			if (api.setStatusBarStyle) {
				api.setStatusBarStyle({
					style: "light"
				});
			}
			this.initEventListenner();

			// 从缓存中获取上一次选择的城市信息
			var currentCity = $kn.getCurrentCityInfo();
			if (!currentCity) {
				this.fnOpenCitySelectorFrame();
				return;
			}
			// 更新界面上显示的城市名称
			this.data.cityName = currentCity.name;
			// 从服务器端更新商品分类列表
			this.fnGetWareTypeList();
		};
		Main.prototype.updatedWareList = function() {
			if (this.data.wareTypeList.length > 0) {
				var wareType = this.data.wareTypeList[this.data.currentIndex];
				this.data.bannerUrl = wareType.banner;
				this.data.wareTypeId = wareType.name == "全部" ? "" : wareType.id;
				this.data.refresherTriggered = true;
				this.fnGetWareList(false);
			}
		};
		Main.prototype.fnGetWareTypeList = function() {
			var that = this;
			$kn.ajax(
				{
					url: "wareTypes/getWareTypeList",
					cache: true
				},
				function(ret, err) {
					if (ret && ret.data) {
						that.data.wareTypeList = ret.data;
						that.updatedWareList();
					} else {
						api.toast({
							msg: "获取商品分类失败",
							duration: 2000,
							location: "bottom"
						});
					}
				}
			);
		};
		Main.prototype.updateShoppingCart = function(param) {
			var that = this;
			var wareId = param.wareId;
			var wareCount = param.wareCount;
			var body = {
				wareId: wareId,
				wareCount: wareCount
			};

			if (param.hasOwnProperty("selected")) {
				body.selected = param.selected;
			}
			$kn.ajax(
				{
					url: "carts/mod",
					method: "post",
					data: {
						body: body
					}
				},

				function(ret, err) {
					if (ret && ret.data) {
						api.setGlobalData({key: "cartInfo", value: ret.data});
						api.sendEvent({
							name: "onGetCartInfo",
							extra: ret.data
						});

						if (that.data.dataList && that.data.dataList.length > 0) {
							that.getFixedWareList(that.data.dataList, ret.data.wareList);
						}
					}
				}
			);
		};
		Main.prototype.initEventListenner = function() {
			var that = this;

			// 监听updateShoppingCart事件（自定义），更新购物车信息
			api.addEventListener(
				{
					name: "updateShoppingCart"
				},
				function(ret, err) {
					that.updateShoppingCart(ret.value);
				}
			);

			// 拦截Android的返回键，在首页点击返回键，提示退出应用
			api.addEventListener(
				{
					name: "keyback"
				},
				function(ret, err) {
					api.confirm(
						{
							title: "提示",
							msg: "是否退出应用",
							buttons: ["确定", "取消"]
						},
						function(ret, err) {
							if (ret.buttonIndex == 1) {
								api.closeWidget({
									silent: true
								});
							}
						}
					);
				}
			);
		};
		Main.prototype.oncityselector = function(e) {
			var currentCity = e.detail;
			if (currentCity && currentCity.name) {
				if (this.data.cityName != currentCity.name) {
					this.data.cityName = currentCity.name;

					if (this.data.wareTypeList.length > 0) {
						this.updatedWareList();
					} else {
						this.fnGetWareTypeList();
					}
				}
			}
			this.data.citySelectorOpened = false;
		};
		Main.prototype.fnOpenCitySelectorFrame = function() {
			this.data.citySelectorOpened = !this.data.citySelectorOpened;
		};
		Main.prototype.fnSetNavMenuIndex = function(e) {
			var index = e.currentTarget.dataset.index;
			if (this.data.currentIndex != index) {
				this.data.currentIndex = index;
				this.updatedWareList();
			}
		};
		Main.prototype.fnOpenPersonalCenterWin = function() {
			var userInfo = $kn.getUserInfo();
			if (userInfo && userInfo.id) {
				api.openWin({
					name: "personalcenter",
					url: "../personalcenter/personalcenter.stml"
				});
			} else {
				// 没有登录，打开登录Window
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});
			}
		};
		Main.prototype.onrefresherrefresh = function() {
			this.data.refresherTriggered = true;
			this.fnGetWareList(false);
		};
		Main.prototype.fnGetWareList = function(loadMore_) {
			// 如果是加载更多，需要实现分页
			var limit = 20;
			if (loadMore_) {
				this.data.skip += limit;
			} else {
				this.data.skip = 0;
			}

			var currentCity = $kn.getCurrentCityInfo();
			var that = this;
			// 根据城市和商品分类获得相应的商品列表
			$kn.ajax(
				{
					url: "wares/getWareList",
					method: "post",
					data: {
						body: {
							supportAreaId: currentCity ? currentCity.id : "",
							wareTypeId: this.data.wareTypeId,
							skip: this.data.skip,
							limit: limit
						}
					}
				},

				function(ret, err) {
					if (ret && ret.data) {
						var cartData = api.getGlobalData({key: "cartInfo"});
						var data = ret.data;
						that.data.haveMoreData = data.length == limit;
						that.getFixedWareList(data, cartData ? cartData.wareList : null);
						if (loadMore_) {
							that.data.dataList = that.data.dataList.concat(data);
						} else {
							that.data.dataList = data;
						}
					} else {
						api.toast({
							msg: "加载数据失败",
							duration: 2000,
							location: "bottom"
						});
					}
					that.data.refreshState = "normal";
					that.data.refresherTriggered = false;
				}
			);
		};
		Main.prototype.getFixedWareList = function(wareList, cartWareList) {
			for (var i = 0; i < wareList.length; i++) {
				var item = wareList[i];
				item.wareCount = 0;
				if (cartWareList && cartWareList.length > 0) {
					for (var j = 0; j < cartWareList.length; j++) {
						var cartItem = cartWareList[j];
						if (cartItem.id == item.id) {
							item.wareCount = cartItem.wareCount;
						}
					}
				}
			}
		};
		Main.prototype.onscrolltolower = function() {
			if (this.data.haveMoreData) {
				this.fnGetWareList(true);
			}
		};
		Main.prototype.fnOpenDetailWin = function(e) {
			var id = e.currentTarget.dataset.id;
			var wareCount = e.currentTarget.dataset.wareCount;

			api.openWin({
				name: "ware" + id,
				url: "../ware/ware.stml",
				pageParam: {
					wareId: id,
					wareCount: wareCount
				},

				animation: {
					type: "fade"
				}
			});
		};
		Main.prototype.fnMinus = function(e) {
			e.stopPropagation && e.stopPropagation();
			if (!$kn.getUserInfo()) {
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});

				return;
			}
			var index = e.currentTarget.dataset.index;
			var item = this.data.dataList[index];
			if (item.wareCount > 0) {
				item.wareCount--;

				this.updateShoppingCart({
					wareId: item.id,
					wareCount: item.wareCount
				});
			}
		};
		Main.prototype.fnAdd = function(e) {
			e.stopPropagation && e.stopPropagation();
			if (!$kn.getUserInfo()) {
				api.openWin({
					name: "login",
					url: "../login/login.stml"
				});

				return;
			}
			var index = e.currentTarget.dataset.index;
			var item = this.data.dataList[index];
			item.wareCount++;

			this.updateShoppingCart({
				wareId: item.id,
				wareCount: item.wareCount
			});
		};
		Main.prototype.render = function() {
			var this$1 = this;
			return apivm.h(
				"view",
				{class: "main"},
				apivm.h(
					"view",
					{class: "header-part"},
					apivm.h("status-bar-view", null),
					apivm.h(
						"view",
						{class: "header-nav"},
						apivm.h(
							"view",
							{
								class: "header-left",
								onclick: function(event) {
									if (this$1.fnOpenCitySelectorFrame) {
										this$1.fnOpenCitySelectorFrame();
									} else {
										fnOpenCitySelectorFrame();
									}
								}
							},
							apivm.h("image", {
								class: this.data.citySelectorOpened
									? "header-left-arrow header-left-arrow-active"
									: "header-left-arrow",
								src: "../../image/arrow_down.png"
							}),
							apivm.h(
								"text",
								{class: "header-left-city", id: "city"},
								this.data.cityName
							)
						),
						apivm.h("text", {class: "header-title"}, "生鲜电商"),
						apivm.h(
							"view",
							{
								class: "header-right",
								onclick: function(event) {
									if (this$1.fnOpenPersonalCenterWin) {
										this$1.fnOpenPersonalCenterWin();
									} else {
										fnOpenPersonalCenterWin();
									}
								}
							},
							apivm.h("image", {
								class: "header-right-icon",
								src: "../../image/home_membercenter.png"
							})
						)
					)
				),
				apivm.h(
					"scroll-view",
					{class: "nav", "scroll-x": "true", "show-scrollbar": "false"},
					Object.entries(this.data.wareTypeList).map(function(ref) {
						var index$1 = ref[0];
						var item$1 = ref[1];
						return apivm.h(
							"text",
							{
								class:
									"nav-menu" +
									(this$1.data.currentIndex == index$1 ? " nav-menu-selected" : ""),
								"data-index": index$1,
								onclick: this$1.fnSetNavMenuIndex
							},
							item$1.name
						);
					})
				),
				apivm.h(
					"scroll-view",
					{
						"scroll-y": "true",
						class: "warelist",
						"enable-back-to-top": true,
						"refresher-enabled": true,
						"refresher-triggered": this.data.refresherTriggered,
						onrefresherrefresh: this.onrefresherrefresh,
						onscrolltolower: this.onscrolltolower
					},
					apivm.h(
						"view",
						{class: "header"},
						apivm.h("image", {
							class: "banner",
							src: this.data.bannerUrl,
							placeholder: "../../image/default_rect.png",
							thumbnail: "false",
							mode: "widthFix"
						})
					),
					apivm.h(
						"view",
						null,
						Object.entries(this.data.dataList).map(function(ref) {
							var index$1 = ref[0];
							var item$1 = ref[1];
							return apivm.h(
								"view",
								{class: "cell"},
								apivm.h(
									"view",
									{
										"data-id": item$1.id,
										"data-wareCount": item$1.wareCount,
										class: "container",
										onclick: this$1.fnOpenDetailWin
									},
									apivm.h("image", {
										class: "thumbnail",
										src: item$1.thumbnail,
										placeholder: "../../image/default_square.png"
									}),
									apivm.h(
										"view",
										{class: "info"},
										apivm.h(
											"text",
											{class: "info-name"},
											item$1.name + " " + (item$1.unit || "")
										),
										apivm.h("text", {class: "info-description"}, item$1.description),
										apivm.h("text", {class: "info-price"}, "￥" + item$1.price),
										apivm.h(
											"text",
											{class: "info-origin-price"},
											"￥" + item$1.originPrice
										)
									),
									apivm.h(
										"view",
										{class: "control"},
										apivm.h("image", {
											class: item$1.wareCount > 0 ? "minus" : "none",
											"data-index": index$1,
											src: "../../image/minus.png",
											onclick: this$1.fnMinus
										}),
										apivm.h(
											"text",
											{class: item$1.wareCount > 0 ? "count" : "none"},
											item$1.wareCount
										),
										apivm.h("image", {
											class: "add",
											"data-index": index$1,
											src: "../../image/add.png",
											onclick: this$1.fnAdd
										})
									)
								)
							);
						})
					),
					apivm.h(
						"view",
						{class: "footer"},
						apivm.h(
							"text",
							{class: "loadDesc"},
							this.data.haveMoreData ? "加载中..." : "没有啦！"
						)
					)
				),
				apivm.h("view", {class: "minicart"}, apivm.h("minicart", null)),
				this.data.citySelectorOpened
					? apivm.h(
							"view",
							{class: "cityselect"},
							apivm.h("cityselector", {
								onresult: function(event) {
									if (this$1.oncityselector) {
										this$1.oncityselector(event);
									} else {
										oncityselector(event);
									}
								}
							})
					  )
					: null
			);
		};

		return Main;
	})(Component);
	apivm.define("main", Main);
	apivm.render(apivm.h("main", null), "body");
})();

	window['createApp'] = function() {
		apivm.$_start();
	}
	return avm;
}